<template>
  <el-select
    filterable
    remote
    reserve-keyword
    default-first-option
    placeholder="请选择退费主体"
    :value="value"
    :remote-method="customerRemoteMethod"
    :loading="loading"
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.customer_name"
      :value="item.id"
      class="refund-item"
    >
      <div class="d-flex">
        <div class="text-truncate flex-1">{{ item.customer_name }}</div>
        <small class="text-muted">{{ item.date }}缴费</small>
      </div>
    </el-option>
  </el-select>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      params: {
        index: 1,
        size: 50,
        'pay_status.gte': 2,
        // 'refund_status.eq': '-1'
      },
      loading: false,
      // 缓存第一次请求数据(customer_name='')
      firstOptions: [],
      options: [],
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    isUserCity() {
      return this.user.orgRegionLever < 3
    },
    isUserProvince() {
      return this.user.orgRegionLever === 1
    },
  },
  watch: {},
  created() {
    if (this.isUserCity) {
      if (this.isUserProvince) {
        this.params['orWhere.pro_service.eq'] = this.clientId
      }
      this.params['orWhere.service_id.eq'] = this.clientId
      this.params['orWhere.recommend_service.eq'] = this.clientId
    } else {
      // 区县端只有直担才有退费管理
      this.params['service_id.eq'] = this.clientId
      this.params['gua_type.eq'] = 2
    }

    this.customerRemoteMethod()
  },
  mounted() {},
  methods: {
    async customerRemoteMethod(query = '') {
      if (!query && this.firstOptions.length) {
        this.options = this.firstOptions
      } else {
        this.options = await this.getData(query)
        if (!query) {
          this.firstOptions = this.options
        }
      }
    },
    async getData(query = '') {
      this.params.customer_name = query
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(
          this.$serviceName,
          'credit_warrant_fee_record_view_db',
          this.params,
          this.order
        )
      )
      this.loading = false
      const data = (res && res.data && res.data.data) || []
      data.forEach(item => {
        item.date = this.$utils.dateFormat(item.actual_warrant_date, 'yyyy年MM月dd日')
      })
      return data
    },
    handleChange(val) {
      const item = this.options.find(it => it.id === val)
      this.$emit('change', val, item)
    },
  },
}
</script>

<style lang="scss" scoped></style>
